
#include "framework/AppThread.h"
#include "msg/MsgHandleBind.h"
#include "timer/TimerManager.h"
namespace KEngine
{
	void AppThread::start()
	{
		if(_running)
			return;
	
		_running = true;
		_thread.runThread(this);
	}

	void AppThread::stop()
	{
		printf("\n app %s stop!",_name.c_str());
		_running = false;
		_thread.endThread();
	}

	AppThread::~AppThread()
	{
		_thread.endThread();
	}

	unsigned long AppThread::threadRun()
	{
		printf("\n app %s start!",_name.c_str());

		_clockMs.restart();

		if(_listener)
			_listener->onStart();

		while(_thread.waitKillEvent(_sleepMs))
		{
			unsigned long timeNow = _clockMs.gettimenow();
			unsigned long elapsed = _clockMs.elapsed();
			_clockMs.restart();

			//run once
			_handlebind->handleOnce();
			_timerManager->run(elapsed,timeNow);
			if(_listener)
				_listener->onRun(elapsed,timeNow);
		}

		if(_listener)
			_listener->onEnd();

		return 0;
	}
};
